package org.zhb.sys.shiro.attachment.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.zhb.sys.core.constant.RetCode;
import org.zhb.sys.core.util.JsonReturn;
import org.zhb.sys.core.util.UUIDUtil;
import org.zhb.sys.core.util.UploadReturn;
import org.zhb.sys.shiro.attachment.service.AttachmentService;
import org.zhb.sys.shiro.model.Attachment;

@RestController
@RequestMapping("/attachment/")
public class AttachmentController {
	@Autowired
	AttachmentService attachmentService;

	@RequestMapping("upload")
	public UploadReturn upload(@RequestParam(value = "imgFile") MultipartFile file, HttpServletRequest request)
			throws IOException {
		UploadReturn uploadReturn = new UploadReturn();
		if (file == null) {
			uploadReturn.setError("0");
			uploadReturn.setMessage("请选择文件");
			uploadReturn.setUrl("");
			return uploadReturn;
		}
		Attachment attachment = new Attachment();
		// 原始名称
		String originalFilename = file.getOriginalFilename();
		attachment.setFileName(originalFilename);// 文件名称
		// 新的图片名称
		String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
		String newFileName = UUIDUtil.getId() + suffix;
		// 文件后缀
		attachment.setSuffix(suffix);
		// 上传日期
		attachment.setCreateDate(new Date());
		// 新的文件
		String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + newFileName;
		// 转存文件
		File newFile = new File(filePath);
		// 文件存放路径
		attachment.setFilePath(filePath);
		// 将内存中的数据写入磁盘
		try {
			file.transferTo(newFile);
			attachmentService.insert(attachment);
			uploadReturn.setError("1");
			uploadReturn.setMessage("上传成功!");
			uploadReturn.setUrl(filePath);
		} catch (IllegalStateException | IOException e) {
			uploadReturn.setError("0");
			uploadReturn.setMessage("上传失败!");
			uploadReturn.setUrl("");
			e.printStackTrace();
		}
		// 文本编辑器上传完成之后,对应的返回数据有
		// error ,url .message
		return uploadReturn;
	}

	/**
	 * @Title: uploadImage
	 * @Description: 带有富文本编辑器的文件上传
	 * @return: Object
	 * @param: @param
	 *             response
	 * @param: @param
	 *             request
	 * @param: @param
	 *             file
	 * @param: @param
	 *             albumId
	 * @param: @return
	 * @author: zhb
	 * @throws 2016年4月7日上午10:18:06
	 */
	@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
	public JsonReturn uploadImage(@RequestParam(value = "imgFile") MultipartFile file, HttpServletRequest request) {
		JsonReturn jsonReturn = new JsonReturn();
		Attachment attachment = new Attachment();
		if (file == null) {
			jsonReturn.setRetcode(RetCode.ERROR_CODE);
			jsonReturn.setRetmsg("请上传文件");
			return jsonReturn;
		}
		String originalFilename = file.getOriginalFilename();
		attachment.setFileName(originalFilename);
		String uploadDir = request.getSession().getServletContext().getRealPath("/upload");
		File dirPath = new File(uploadDir);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}
		String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
		attachment.setSuffix(suffix);
		String newFileName = UUIDUtil.getId() + "." + suffix;
		// 上传日期
		attachment.setCreateDate(new Date());
		// 新的文件
		String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + newFileName;
		// 转存文件
		File newFile = new File(filePath);
		// 文件存放路径
		attachment.setFilePath(filePath);
		// 将内存中的数据写入磁盘
		try {
			file.transferTo(newFile);
			attachmentService.insert(attachment);
			jsonReturn.setRetcode(RetCode.OK_CODE);
			jsonReturn.setRetmsg("上传成功");
		} catch (IllegalStateException | IOException e) {
			jsonReturn.setRetcode(RetCode.ERROR_CODE);
			jsonReturn.setRetmsg("上传失败");
			e.printStackTrace();
		}
		return jsonReturn;
	}

	/**
	 * @Title: downloadAttachment
	 * @Description: 文件下载
	 * @return: ResponseEntity<byte[]>
	 * @param: @param
	 *             attachmentId
	 * @param: @param
	 *             response
	 * @param: @param
	 *             request
	 * @param: @return
	 * @author: zhb
	 * @throws 2016年4月6日下午5:30:14
	 */
	@RequestMapping(value = "/download/{attachmentId}")
	public ResponseEntity<byte[]> downloadAttachment(@PathVariable("attachmentId") String attachmentId,
			HttpServletResponse response, HttpServletRequest request) {
		try {
			Attachment attachment = attachmentService.findById(attachmentId);
			String filePath;
			if (attachment == null || StringUtils.isBlank(attachment.getFilePath())) {
				filePath = request.getServletContext().getRealPath("/resources/images/no_image.jpg");
			} else {
				filePath = attachment.getFilePath();
			}
			File file = new File(filePath);
			if (!file.exists()) {
				return null;
			}
			String name = file.getName();
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.setContentLength(file.length());
			headers.setContentDispositionFormData("attachment", new String(name.getBytes("gbk"), "iso-8859-1"));
			FileSystem fileSystem = FileSystems.getDefault();
			Path path = fileSystem.getPath(filePath);
			byte[] readAllBytes = Files.readAllBytes(path);
			ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(readAllBytes, headers, HttpStatus.CREATED);
			return responseEntity;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @Title: deleteFile
	 * @Description:文件删除
	 * @return: String
	 * @param: @return
	 * @author: zhb
	 * @throws 2016年4月6日下午5:31:16
	 */
	@RequestMapping("delFile")
	public String deleteFile() {
		return null;
	}
}
